package com.share.config.kafka;

import com.share.common.enums.KafkaTopicEnum;
import org.apache.kafka.clients.admin.AdminClientConfig;
import org.apache.kafka.clients.admin.NewTopic;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.KafkaAdmin;

import java.util.HashMap;
import java.util.Map;

/**
 * 开启topic自动创建---kafak需要开启自动创建功能
 */
@Configuration
public class AutoCreateTopic {
    @Value(value = "${spring.kafka.bootstrap-servers}")
    private String bootstrapAddress;

    private NewTopic getTopic(KafkaTopicEnum en) {
        return new NewTopic(en.code, en.numPartitions, en.replicationFactor);
    }

    @Bean
    public KafkaAdmin kafkaAdmin() {
        Map<String, Object> configs = new HashMap<>();
        configs.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress);
        return new KafkaAdmin(configs);
    }

    @Bean
    public NewTopic initTopic1() {
        return getTopic(KafkaTopicEnum.CREDIT);
    }

    @Bean
    public NewTopic initTopic2() {
        return getTopic(KafkaTopicEnum.PRE_CREDIT);
    }

    @Bean
    public NewTopic initTopic3() {
        return getTopic(KafkaTopicEnum.LOAN);
    }

    @Bean
    public NewTopic initTopic4() {
        return getTopic(KafkaTopicEnum.PRE_LOAN);
    }
}
